// 文件用途：敏感词过滤工具（仅注释，不改逻辑）
// 功能概览：
// - 启动时从后端加载敏感词列表（active 状态）并存入 ref
// - 提供 filter/contains/find 三个方法用于替换、判断与提取
// - 后端不可用时提供内置演示数据，保证功能演示
import { ref } from 'vue'
import { api } from './api'

export const sensitiveWords = ref([])

// 从服务器获取敏感词列表
// 拉取敏感词列表：兼容多种返回结构（数组 / {data:[]} / {wordList:[]})
export async function loadSensitiveWords() {
  try {
    console.log('开始加载敏感词列表...')
    console.log('API基础URL:', import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080')
    
    const response = await api.get('/sensitive-word/list/active')
    console.log('敏感词API原始响应:', response)
    console.log('响应类型:', typeof response)
    console.log('是否为数组:', Array.isArray(response))
    
    // 处理响应数据
    let wordList = []
    if (Array.isArray(response)) {
      wordList = response
      console.log('直接使用响应数组:', wordList)
    } else if (response && Array.isArray(response.data)) {
      wordList = response.data
      console.log('使用响应的data字段:', wordList)
    } else if (response && Array.isArray(response.wordList)) {
      wordList = response.wordList
      console.log('使用响应的wordList字段:', wordList)
    } else {
      console.warn('无法解析敏感词响应格式:', response)
      console.warn('响应的所有键:', Object.keys(response || {}))
      throw new Error('无法解析敏感词响应格式')
    }
    
    console.log('解析到的敏感词列表:', wordList)
    console.log('列表长度:', wordList.length)
    
  // 转换格式并过滤有效的敏感词（仅保留 status=active 且有 word 的项）
     const processedWords = wordList
       .filter(item => {
         console.log('处理敏感词项:', item)
         const isValid = item && typeof item === 'object' && item.word && item.word.trim() && item.status === 'active'
         console.log('敏感词项是否有效:', isValid)
         return isValid
       })
       .map(item => ({
         word: item.word.trim(),
         status: item.status,
         wordId: item.wordId
       }))
    
    console.log('处理后的敏感词列表:', processedWords)
    console.log('有效敏感词数量:', processedWords.length)
    
    sensitiveWords.value = processedWords
    console.log('敏感词加载完成，共', sensitiveWords.value.length, '个敏感词')
    console.log('最终敏感词列表:', sensitiveWords.value)
  } catch (error) {
    console.error('加载敏感词失败:', error)
    console.error('错误详情:', error.message)
    console.error('错误堆栈:', error.stack)
    console.log('后端服务不可用，使用默认敏感词进行演示')
    // 使用默认敏感词，包含测试数据中的敏感词
    sensitiveWords.value = [
      { word: '敏感词', status: 'active', wordId: 1 },
      { word: '违禁词', status: 'active', wordId: 2 },
      { word: '不当言论', status: 'active', wordId: 3 },
      { word: '垃圾信息', status: 'active', wordId: 4 },
      { word: '广告', status: 'active', wordId: 5 }
    ]
    console.log('使用默认敏感词:', sensitiveWords.value)
  }
}

// 过滤敏感词：默认替换为***；若 action=block 则返回屏蔽文案
export function filterSensitiveWords(content) {
  if (!content) return ''
  
  let result = content
  
  sensitiveWords.value.forEach(wordObj => {
    if (wordObj && wordObj.word && wordObj.status === 'active') {
      const word = wordObj.word
      const replacement = wordObj.replacement || '***'
      const action = wordObj.action || 'replace'
      
      if (action === 'replace') {
        // 全局替换，忽略大小写
        const regex = new RegExp(word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi')
        result = result.replace(regex, replacement)
      } else if (action === 'block') {
        if (result.toLowerCase().includes(word.toLowerCase())) {
          return '[内容包含敏感词，已被屏蔽]'
        }
      }
    }
  })
  
  return result
}

// 检查是否包含敏感词：忽略大小写
export function containsSensitiveWords(content) {
  if (!content) return false
  
  const lowerContent = content.toLowerCase()
  
  return sensitiveWords.value.some(wordObj => {
    return wordObj && 
           wordObj.word && 
           wordObj.status === 'active' && 
           lowerContent.includes(wordObj.word.toLowerCase())
  })
}

// 获取内容中的敏感词：返回命中的词列表
export function findSensitiveWords(content) {
  if (!content) return []
  
  const lowerContent = content.toLowerCase()
  const foundWords = []
  
  sensitiveWords.value.forEach(wordObj => {
    if (wordObj && 
        wordObj.word && 
        wordObj.status === 'active' && 
        lowerContent.includes(wordObj.word.toLowerCase())) {
      foundWords.push(wordObj.word)
    }
  })
  
  return foundWords
}

// 初始化敏感词：模块加载时即触发
loadSensitiveWords()
